package me.zhengjie.modules.hanzi.service;

import me.zhengjie.modules.hanzi.config.AiServiceProperties.AiProviderConfig;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * AI服务API路径构建器
 * 根据不同的AI服务类型构建正确的API路径
 */
@Component
public class AiApiPathBuilder {
    
    /**
     * 构建聊天完成API路径
     * @param config AI服务提供商配置
     * @return 完整的API路径
     */
    public String buildChatCompletionsPath(AiProviderConfig config) {
        String apiType = config.getApiType();
        Map<String, Object> apiPaths = config.getApiPaths();
        
        switch (apiType.toLowerCase()) {
            case "gemini":
                return buildGeminiPath(config, apiPaths, "generate-content");
            case "hf":
                return getNestedPath(apiPaths, "hf", "chat-completions");
            case "openai":
            default:
                return getNestedPath(apiPaths, "openai", "chat-completions", 
                                   () -> getSimplePath(apiPaths, "chat-completions", "/v1/chat/completions"));
        }
    }
    
    /**
     * 构建模型列表API路径
     * @param config AI服务提供商配置
     * @return 完整的API路径
     */
    public String buildModelsPath(AiProviderConfig config) {
        String apiType = config.getApiType();
        Map<String, Object> apiPaths = config.getApiPaths();
        
        switch (apiType.toLowerCase()) {
            case "gemini":
                return getNestedPath(apiPaths, "gemini", "models");
            case "hf":
                return getNestedPath(apiPaths, "hf", "models");
            case "openai":
            default:
                return getNestedPath(apiPaths, "openai", "models", 
                                   () -> getSimplePath(apiPaths, "models", "/v1/models"));
        }
    }
    
    /**
     * 构建嵌入API路径
     * @param config AI服务提供商配置
     * @return 完整的API路径
     */
    public String buildEmbeddingsPath(AiProviderConfig config) {
        String apiType = config.getApiType();
        Map<String, Object> apiPaths = config.getApiPaths();
        
        switch (apiType.toLowerCase()) {
            case "gemini":
                // Gemini 通常不支持单独的嵌入API，使用generateContent
                return buildGeminiPath(config, apiPaths, "generate-content");
            case "hf":
                return getNestedPath(apiPaths, "hf", "embeddings");
            case "openai":
            default:
                return getNestedPath(apiPaths, "openai", "embeddings", 
                                   () -> getSimplePath(apiPaths, "embeddings", "/v1/embeddings"));
        }
    }
    
    /**
     * 构建Gemini特定的API路径
     */
    private String buildGeminiPath(AiProviderConfig config, Map<String, Object> apiPaths, String endpoint) {
        String pathTemplate = getNestedPath(apiPaths, "gemini", endpoint);
        if (pathTemplate != null && pathTemplate.contains("{model}")) {
            return pathTemplate.replace("{model}", config.getModel());
        }
        return pathTemplate;
    }
    
    /**
     * 获取嵌套路径（支持api-paths中的分组配置）
     */
    @SuppressWarnings("unchecked")
    private String getNestedPath(Map<String, Object> apiPaths, String group, String endpoint) {
        return getNestedPath(apiPaths, group, endpoint, null);
    }
    
    /**
     * 获取嵌套路径，带回退逻辑
     */
    @SuppressWarnings("unchecked")
    private String getNestedPath(Map<String, Object> apiPaths, String group, String endpoint, Runnable fallback) {
        if (apiPaths == null) {
            if (fallback != null) {
                fallback.run();
            }
            return null;
        }
        
        Object groupObj = apiPaths.get(group);
        if (groupObj instanceof Map) {
            Map<String, Object> groupPaths = (Map<String, Object>) groupObj;
            Object pathObj = groupPaths.get(endpoint);
            if (pathObj instanceof String) {
                return (String) pathObj;
            }
        }
        
        if (fallback != null) {
            fallback.run();
        }
        return null;
    }
    
    /**
     * 获取简单路径（直接从根级别获取）
     */
    private String getSimplePath(Map<String, Object> apiPaths, String key, String defaultPath) {
        if (apiPaths == null) {
            return defaultPath;
        }
        
        Object pathObj = apiPaths.get(key);
        if (pathObj instanceof String) {
            return (String) pathObj;
        }
        
        return defaultPath;
    }
    
    /**
     * 构建完整URL
     * @param baseUrl 基础URL
     * @param path API路径
     * @return 完整URL
     */
    public String buildFullUrl(String baseUrl, String path) {
        if (baseUrl == null || path == null) {
            throw new IllegalArgumentException("Base URL and path cannot be null");
        }
        
        String cleanBaseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
        String cleanPath = path.startsWith("/") ? path : "/" + path;
        
        return cleanBaseUrl + cleanPath;
    }
}